package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.feigns.admin.AdminFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.constants.ArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Version: V1.0
 */
@Service
@Slf4j
public class HotArticleServiceImpl implements HotArticleService {


    @Autowired
    ApArticleMapper apArticleMapper;

    @Autowired
    AdminFeign adminFeign;

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 定时计算热点文章 （XXL-JOB）
     */
    @Override
    public void computeHotArticle() {

        //1 获取前5天的文章
        String dateParam = DateTime.now().minusDays(5).toString("yyyy-MM-dd 00:00:00");
        List<ApArticle> articleList = apArticleMapper.selectList(Wrappers.<ApArticle>lambdaQuery()
                .ge(ApArticle::getPublishTime, dateParam));

        //2 计算文章的分值
        List<HotArticleVo> articleScoreList = computeArticleScore(articleList);
        if (articleScoreList == null) {
            log.info("HotArticleServiceImpl computeHotArticle  Article is null, time:{}", dateParam);
            return;
        }


        //3 查询所有频道 缓存频道下的热点文章列表
        // 30条， 默认频道数据（所有文章的前30条）， 频道下对应的列表， 按照分值排序
        cacheTagToRedis(articleScoreList);

        log.info("**************computeHotArticle cacheTagToRedis is success**************");
    }

    /**
     * 缓存热点文章
     * @param articleScoreList 带分值的文章列表（未排序）
     */
    private void cacheTagToRedis(List<HotArticleVo> articleScoreList) {

        //1 查询所有的频道列表
        ResponseResult result = adminFeign.findAll();
        if (result.getCode() == 0) {

            //2 遍历频道列表，筛选当前频道下的文章
            List<AdChannel> channelList = JSON.parseArray(JSON.toJSONString(result.getData()), AdChannel.class);

            //3 给每个频道下的文章进行缓存(已排序)
            for (AdChannel adChannel : channelList) {

                // 得到每个频道下的文章
                List<HotArticleVo> channelArticleVoList = articleScoreList.stream()
                        .filter(articleScore -> articleScore.getChannelId().equals(adChannel.getId()))
                        .collect(Collectors.toList());

                sortAndCache(channelArticleVoList, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + adChannel.getId());
            }
        }

        //4 给推荐频道缓存30条数据  所有文章排序之后的前30条
        sortAndCache(articleScoreList, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);
    }

    /**
     * 缓存热点文章到redis， 有排序
     * @param articleScoreList
     * @param key
     */
    private void sortAndCache(List<HotArticleVo> articleScoreList, String key) {

        // 排序
        articleScoreList = articleScoreList.stream().sorted(Comparator.comparing(HotArticleVo::getScore)
                .reversed()).collect(Collectors.toList());
        // .limit(30)

        if (articleScoreList.size() > 30) {
            articleScoreList = articleScoreList.subList(0, 30);
        }

        redisTemplate.opsForValue().set(key, JSON.toJSONString(articleScoreList));
    }

    /**
     * 计算文章分值
     * @param articleList
     * @return
     */
    private List<HotArticleVo> computeArticleScore(List<ApArticle> articleList) {

        List<HotArticleVo> hotArticleVos = new ArrayList<>();

        if (articleList != null && articleList.size() > 0) {

            for (ApArticle apArticle : articleList) {

                HotArticleVo hotArticleVo = new HotArticleVo();
                BeanUtils.copyProperties(apArticle, hotArticleVo);

                // 计算每一篇文章的分数
                int score = computeScore(apArticle);
                hotArticleVo.setScore(score);

                // 添加集合
                hotArticleVos.add(hotArticleVo);
            }

            return hotArticleVos;
        }
        return null;
    }

    /**
     * 计算文章分值方法     阅读：1，点赞：3，评论：5，收藏：8
     * @param apArticle
     * @return
     */
    private int computeScore(ApArticle apArticle) {

        int score = 0;

        if (apArticle.getViews() != null) {
            score += apArticle.getViews().intValue() * ArticleConstants.HOT_ARTICLE_VIEW_WEIGHT;
        }

        // 点赞 3
        if (apArticle.getLikes() != null) {
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        // 评论 5
        if (apArticle.getComment() != null) {
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        // 收藏 8
        if (apArticle.getCollection() != null) {
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }

        return score;
    }
}
